/**
 * ytree
 * @author  yan
 * @data 2014-03-11
 *
 */

define(['jquery'], function($) {
  'use strict';
  /**
   * helper
   */

  function isUndefined(obj) {
    return typeof obj === 'undefined'
  }

  /**
   * namesapce tree
   */
  var tree = {
    defaults: {
      plugins: []
    },
    // 可用插件。通过 tree.plugins.pluginName 扩展
    plugins: {},
    node: {
      text: '',
      href: '#',
      stats: {
        hasChildren: false,
        opened: false,
        selected: false,
        checked: false
      }
    }
  }

  tree.create = function(elem, options) {
    var mytree = new tree.core()
    var settings = $.extend(true, {}, tree.defaults, options)
    $.each(settings.plugins, function(key, val) {
      if (key !== 'core') {
        mytree = mytree.plugin(val, settings[val])
      }
    })
    mytree.init(elem, settings)
    return mytree
  }

  /**
   * exports
   * @param  {dom|selector} elem  树容器
   * @param  {object} options 选项
   * @return {}         [description]
   */

  function ytree(elem, options) {
    return tree.create(elem, options)
  }

  /**
   * core
   */
  tree.defaults.core = {}

  tree.core = function() {
    this.model = {
      selected: [],
      checked: []
    }
  }

  $.extend(tree.core.prototype, {
    plugin: function(name, options) {
      var Child = tree.plugins[name]
      if (Child) {
        Child.prototype = this
        return new Child(options, this)
      }
      return this
    },
    init: function(elem, options) {
      this.options = options
      this.$element = $(elem)
        .attr('role', 'tree')
        .html('<ul class="ytree ytree-wholerow"><li>loading</li></ul>')
      this.$tree = this.$element.children('.ytree')
      this._bind()
      this.load()
    },
    _bind: function() {
      this.$element
        .on('click', '.oc', $.proxy(function(e) {
         // this.toggle(e.target)
        }, this))
        .on('click', '.anchor', function(e) {
          e.preventDefault()
        })
    },
    _klass: function(stats) {
      var arr = []
      if (stats.hasChildren) {
        arr.push('b')
      }
      if (stats.opened) {
        arr.push('open')
      }
      if (stats.selected) {
        arr.push('selected')
      }
      if (stats.checked) {
        arr.push('checked')
      }
      return arr.join(' ')
    },
    _li: function(obj) {
      var className = ' class="' + this._klass(obj.stats) + '"'
      var dataref = ' data-ref="' + obj.ref + '"'
      var a = '<a href="#"   data='+obj.id+'     class="a">' +
        (this.options.checkbox ? '<i class="icon-checkbox"></i>' : '') +
        obj.text + '</a>'
      var li = '<li   data='+obj.id+' title="'+obj.id+'" ' + className + dataref + '>' +
          '<p class="bg"></p>' +
          '<i class="oc"></i>' + a
      if (obj.stats.hasChildren) {
        li += '<ul>'
      } else {
        li += '</li>'
      }

      return li
    },
    _html: function(nodes, parentRef, html) {
      html = html || ''
      parentRef = parentRef ? parentRef + '_' : ''
      for (var i = 0, len = nodes.length; i < len; i++) {
        // TODO: 更好的方法？
        var obj = $.extend(true, {}, tree.node, nodes[i])
        var children = obj.children
        var ref = parentRef + i
        obj.ref = ref

        if (obj.stats.selected) {
          this.model.selected.push(ref)
        }

        if (obj.stats.checked) {
          this.model.checked.push(ref)
        }

        this.model[ref] = obj

        // 是否要判断 length
        // TODO： 节点数
        if (children && children.length) {
          var obj2 = obj
          obj2.stats.hasChildren = true
          delete obj2.children
          this.model[ref] = obj2

          html += this._li(obj2)
          html = this._html(children, ref, html) + '</ul></li>'
        } else {
          html += this._li(obj)
        }
      }
      return html
    },
    load: function() {
      var options = this.options
      var html = this._html(options.data)
      this.$tree.html(html)
    },
    toggle: function(elem) {
     
      //$(elem).parent().toggleClass('open')
      $(elem).parent().toggleClass('open')
      
    },
    // 局部更新或全部更新
    refresh: function(parentRef) {
      // var html = this._html
    }
  })

  /**
   * plugin checkbox
   */
  tree.defaults.checkbox = {}

  tree.plugins.checkbox = function(parent, options) {
    this.bind = function() {
      parent._bind.call(this)
    }
  }

  return ytree
})
